package ConcurrentHashMap_10;
import java.util.concurrent.ConcurrentHashMap;
public class 遍历操作_线程安全迭代 {
    public static void main(String[] args) {
        final ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();
        final int ENTRY_COUNT = 100;

        // 初始化Map
        for (int i = 0; i < ENTRY_COUNT; i++) {
            map.put(i, "Value-" + i);
        }

        // 创建10个读写混合线程
        for (int i = 0; i < 10; i++) {
            final int threadId = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        // 写入操作
                        if (threadId % 3 == 0) {
                            int key = ENTRY_COUNT + threadId;
                            map.put(key, "New-Value-" + key);
                            System.out.println(Thread.currentThread().getName() + " 添加新键: " + key);
                            Thread.sleep(10);
                        }
                        // 读取操作
                        else {
                            // 安全遍历 - 不需要额外同步
                            for (java.util.Map.Entry<Integer, String> entry : map.entrySet()) {
                                System.out.println(Thread.currentThread().getName() +
                                                           " 遍历: " + entry.getKey() + "=" + entry.getValue());
                                Thread.sleep(1); // 模拟处理时间
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "线程-" + i).start();
        }
    }
}